import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, Select, Space, Tag, Modal, message, Descriptions, Switch, Row, Col } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import { request } from 'umi';

const { Option } = Select;
const { TextArea } = Input;

// 获取会员权益列表
const fetchRights = async (params) => {
  return request('/api/v1/member/rights', {
    method: 'GET',
    params,
  });
};

// 获取会员权益详情
const fetchRightDetail = async (id) => {
  return request(`/api/v1/member/rights/${id}`, {
    method: 'GET',
  });
};

// 创建会员权益
const createRight = async (data) => {
  return request('/api/v1/member/rights', {
    method: 'POST',
    data,
  });
};

// 更新会员权益
const updateRight = async (data) => {
  return request('/api/v1/member/rights', {
    method: 'PUT',
    data,
  });
};

// 删除会员权益
const deleteRight = async (id) => {
  return request(`/api/v1/member/rights/${id}`, {
    method: 'DELETE',
  });
};

const MemberRights = () => {
  const [rights, setRights] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [rightForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchParams, setSearchParams] = useState({});
  const [detailVisible, setDetailVisible] = useState(false);
  const [formVisible, setFormVisible] = useState(false);
  const [currentRight, setCurrentRight] = useState(null);
  const [formTitle, setFormTitle] = useState('创建会员权益');

  // 获取会员权益列表
  const fetchRightList = async () => {
    try {
      setLoading(true);
      const res = await fetchRights({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
      });
      if (res.success) {
        setRights(res.data.list || []);
        setPagination({
          ...pagination,
          total: res.data.total,
        });
      } else {
        message.error(res.message || '获取会员权益列表失败');
      }
    } catch (error) {
      console.error('获取会员权益列表出错:', error);
      message.error('获取会员权益列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchRightList();
  }, [pagination.current, pagination.pageSize, searchParams]);

  // 查看权益详情
  const handleViewDetail = async (record) => {
    try {
      setLoading(true);
      const res = await fetchRightDetail(record.id);
      if (res.success) {
        setCurrentRight(res.data);
        setDetailVisible(true);
      } else {
        message.error(res.message || '获取权益详情失败');
      }
    } catch (error) {
      console.error('获取权益详情出错:', error);
      message.error('获取权益详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理添加权益
  const handleAdd = () => {
    setFormTitle('创建会员权益');
    setCurrentRight(null);
    rightForm.resetFields();
    rightForm.setFieldsValue({
      status: true,
    });
    setFormVisible(true);
  };

  // 处理编辑权益
  const handleEdit = (record) => {
    setFormTitle('编辑会员权益');
    setCurrentRight(record);
    rightForm.resetFields();
    rightForm.setFieldsValue({
      name: record.name,
      description: record.description,
      levelId: record.levelId,
      status: record.status === 1,
    });
    setFormVisible(true);
  };

  // 处理删除权益
  const handleDelete = async (id) => {
    try {
      setLoading(true);
      const res = await deleteRight(id);
      if (res.success) {
        message.success('删除会员权益成功');
        fetchRightList();
      } else {
        message.error(res.message || '删除会员权益失败');
      }
    } catch (error) {
      console.error('删除会员权益出错:', error);
      message.error('删除会员权益失败');
    } finally {
      setLoading(false);
    }
  };

  // 提交表单
  const handleFormSubmit = async () => {
    try {
      const values = await rightForm.validateFields();
      setLoading(true);
      
      // 设置状态
      values.status = values.status ? 1 : 0;
      
      let res;
      if (currentRight) {
        // 更新
        res = await updateRight({
          id: currentRight.id,
          ...values,
        });
      } else {
        // 创建
        res = await createRight(values);
      }
      
      if (res.success) {
        message.success(`${currentRight ? '更新' : '创建'}会员权益成功`);
        setFormVisible(false);
        fetchRightList();
      } else {
        message.error(res.message || `${currentRight ? '更新' : '创建'}会员权益失败`);
      }
    } catch (error) {
      console.error(`${currentRight ? '更新' : '创建'}会员权益出错:`, error);
      message.error(`${currentRight ? '更新' : '创建'}会员权益失败`);
    } finally {
      setLoading(false);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '权益名称',
      dataIndex: 'name',
      key: 'name',
      width: 180,
    },
    {
      title: '适用等级',
      dataIndex: 'levelName',
      key: 'levelName',
      width: 120,
    },
    {
      title: '权益描述',
      dataIndex: 'description',
      key: 'description',
      width: 300,
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <Card title="会员权益配置" extra={<Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>添加权益</Button>}>
        <Table
          columns={columns}
          dataSource={rights}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={(pagination) => setPagination(pagination)}
        />
      </Card>

      <Modal
        title={formTitle}
        visible={formVisible}
        onCancel={() => setFormVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setFormVisible(false)}>
            取消
          </Button>,
          <Button key="submit" type="primary" loading={loading} onClick={handleFormSubmit}>
            提交
          </Button>,
        ]}
      >
        <Form form={rightForm} layout="vertical">
          <Form.Item
            name="name"
            label="权益名称"
            rules={[{ required: true, message: '请输入权益名称' }]}
          >
            <Input placeholder="请输入权益名称" />
          </Form.Item>
          <Form.Item
            name="levelId"
            label="适用等级"
            rules={[{ required: true, message: '请选择适用等级' }]}
          >
            <Select placeholder="请选择适用等级">
              <Option value={1}>普通会员</Option>
              <Option value={2}>银卡会员</Option>
              <Option value={3}>金卡会员</Option>
              <Option value={4}>钻石会员</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="description"
            label="权益描述"
            rules={[{ required: true, message: '请输入权益描述' }]}
          >
            <TextArea rows={4} placeholder="请输入权益描述" />
          </Form.Item>
          <Form.Item name="status" valuePropName="checked" label="状态">
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="权益详情"
        visible={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={null}
      >
        {currentRight && (
          <Descriptions bordered column={1}>
            <Descriptions.Item label="权益名称">{currentRight.name}</Descriptions.Item>
            <Descriptions.Item label="适用等级">{currentRight.levelName}</Descriptions.Item>
            <Descriptions.Item label="权益描述">{currentRight.description}</Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={currentRight.status === 1 ? 'green' : 'red'}>
                {currentRight.status === 1 ? '启用' : '禁用'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">{currentRight.createdAt}</Descriptions.Item>
            <Descriptions.Item label="更新时间">{currentRight.updatedAt}</Descriptions.Item>
          </Descriptions>
        )}
      </Modal>
    </PageContainer>
  );
};

export default MemberRights;